/**
 * @Date: Feb 19, 2010 7:09:15 PM
 */
package com.philip.journal.login.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.philip.journal.core.bean.User;
import com.philip.journal.core.controller.BaseServlet;
import com.philip.journal.core.controller.SessionConstant;

/**
 * TODO: Has JSON calls that can be refactored out.
 *
 * @author cry30
 */
public class LoginServlet extends BaseServlet {

    /** Login page relative uri. */
    private static final String LOGIN_PAGE = "/WEB-INF/pages/login/login.jsp";

    @Override
    public void service(final HttpServletRequest request, final HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("logout") != null) { // NOPMD by r39 on 3/30/11 1:47 PM
            request.getSession().removeAttribute(SessionConstant.USER);
            request.getSession().invalidate();
            response.sendRedirect(request.getContextPath() + "/home");
        } else if (request.getSession().getAttribute(SessionConstant.USER) != null) { // NOPMD by r39 on 3/30/11 1:47 PM
            getLogger().debug("User already authenticated.  Forwarding to home page.");
            response.sendRedirect(request.getContextPath() + "/home");
        } else if (request.getMethod().equalsIgnoreCase(METHOD_POST)) {
            final String username = request.getParameter(LoginFieldname.USERNAME);
            final String password = request.getParameter(LoginFieldname.PASSWORD);
            getLogger().info("username: " + username);

            final PrintWriter printWriter = response.getWriter();
            String errorMsg = null;
            try {
                getServiceProxy().setSessionId(request.getSession().getId());
                final User user = getServiceProxy().authenticateUser(username, password);
                request.getSession().setAttribute(SessionConstant.USER, user);
                printWriter.write("{success: true, redirect: '" + request.getContextPath() + "/home" + "'}");
                getLogger().debug("LOGIN SUCCESS");
                return;
            } catch (final Exception e) { // catch All
                if (e.getCause() == null) {
                    errorMsg = e.getMessage();
                } else {
                    errorMsg = e.getCause().getMessage();
                }
                getLogger().debug(errorMsg, e);
            }


            printWriter.write("{ success: false, errors: {reason: 'Login failed. " + errorMsg + "' }}");
        } else {
            request.getRequestDispatcher(LOGIN_PAGE).include(request, response);
        }
    }
}
